package str85_mapowanie_plikow_nio;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.zip.CRC32;

import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import javax.swing.filechooser.FileFilter;

public class Main {
	public static long checksumInputStream(String filename) 
			throws IOException {
		InputStream in = new FileInputStream(filename);
		CRC32 crc = new CRC32();
		
		int c;
		while ((c = in.read()) != -1)
			crc.update(c);
		
		return crc.getValue();
	}
	
	public static long checksumBufferedInputStream(String filename)
			throws IOException {
		InputStream in = new BufferedInputStream(
				new FileInputStream(filename));
		CRC32 crc = new CRC32();
		
		int c; 
		while ((c = in.read()) != -1)
			crc.update(c);

		return crc.getValue();
	}
	
	public static long checksumRandomAccessFile(String filename) 
			throws IOException {
		RandomAccessFile file = new RandomAccessFile(filename, "r");
		long length = file.length();
		CRC32 crc = new CRC32();
		
		for (long p = 0; p < length; p++) {
			file.seek(p);
			int c = file.readByte();
			crc.update(c);
		}
		
		return crc.getValue();
	}
	
	public static long checksumMappedFile(String filename)
			throws IOException {
		FileInputStream fis = new FileInputStream(filename);
		FileChannel channel = fis.getChannel();
		
		CRC32 crc = new CRC32();
		int length = (int)channel.size();
		
		MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
		
		for (int i = 0; i < length; i++) {
			int c = buffer.get(i);
			crc.update(c);
		}
		
		return crc.getValue();
	}
	
	public static void main(String[] args) 
			throws IOException, ClassNotFoundException, InstantiationException,
			IllegalAccessException, UnsupportedLookAndFeelException {
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileFilter(new FileFilter() {
			String descpription = ".jar";
			
			@Override
			public String getDescription() {
				return descpription;
				
			}
			
			@Override
			public boolean accept(File f) {
				String fileName = f.getName();
				return fileName.endsWith(descpription) || f.isDirectory();
				
			}
		});
		
		int result = fileChooser.showOpenDialog(null);
		
		if (result == JFileChooser.APPROVE_OPTION) {
			String filePath = fileChooser.getSelectedFile().getCanonicalPath();
			
			Ramka ramka = new Ramka(filePath);
			ramka.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
			ramka.setVisible(true);
		}
		
		
	}
}
